# -*- coding: UTF-8 -*-
import random
import numpy as np
import math
from taxi_special import square


CONSTANTS_RADIUS_OF_EARTH = 6371000
def gps2xy(lat, lon):
    lat_min,lon_min,lat_max,lon_max = square()
    # 参考点，就当原点吧
    ref_lat = lat_min
    ref_lon = lon_min

    lat_rad = math.radians(lat)
    lon_rad = math.radians(lon)
    ref_lat_rad = math.radians(ref_lat)
    ref_lon_rad = math.radians(ref_lon)

    sin_lat = math.sin(lat_rad)
    cos_lat = math.cos(lat_rad)
    ref_sin_lat = math.sin(ref_lat_rad)
    ref_cos_lat = math.cos(ref_lat_rad)

    cos_d_lon = math.cos(lon_rad - ref_lon_rad)

    arg = np.clip(ref_sin_lat * sin_lat + ref_cos_lat * cos_lat * cos_d_lon, -1.0, 1.0)
    c = math.acos(arg)

    k = 1.0
    if abs(c) > 0:
        k = (c / math.sin(c))

    x = float(k * (ref_cos_lat * sin_lat - ref_sin_lat * cos_lat * cos_d_lon) * CONSTANTS_RADIUS_OF_EARTH)
    y = float(k * cos_lat * math.sin(lon_rad - ref_lon_rad) * CONSTANTS_RADIUS_OF_EARTH)

    return x, y

def normalizeGPS(lat,lon): 
    x_lat,y_lon = gps2xy(lat,lon)
    lat_min,lon_min,lat_max,lon_max = square()
    maxX,maxY = gps2xy(lat_max,lon_max)
    minX,minY = gps2xy(lat_min,lon_min)
    diagonal = math.sqrt((maxX-minX)*(maxX-minX) + (maxY-minY)*(maxY-minY))
    narm_x_lat = (x_lat - minX)/diagonal
    narm_y_lon = (y_lon - minY)/diagonal
    return narm_x_lat,narm_y_lon
